package cn.wolfcode.luowowo.member.service.impl;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AssertUtil;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.mapper.UserInfoMapper;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UserServiceImpl implements IUserInfoService{

    private static int RESGITCODE = 1;
    private static int UPDATEPASSWORD=0;
    public static final int LOGOFFSTATE=-1;
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public UserInfo getUserInfoById(Long userInfoId) {
        return userInfoMapper.selectByPrimaryKey(userInfoId);
    }

    @Override
    public Boolean checkPhone(String phone) {
        int count = userInfoMapper.selectByPhone(phone);
        if(count == 1)
            return true;
        return false;
    }

    @Override
    public void sendVerifyCode(String phone,int type) {
        //验证码
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
        //创建短信
        StringBuilder stringBuilder = new StringBuilder(100);
        if (type==RESGITCODE){
            stringBuilder.append("骡窝窝的注册验证码为："+code+",请在"+ Consts.VERIFY_CODE_VAI_TIME+"分钟内使用");
        }
        if (type==UPDATEPASSWORD) {
            stringBuilder.append("您正在更改密码,骡窝窝的验证码为：" + code + ",请在" + Consts.VERIFY_CODE_VAI_TIME + "分钟内使用");
        }
        System.out.println(stringBuilder);

        //将验证码缓存到redis
        //redis 设计：key ：前缀+手机号码  value：验证码 设置过期时间
        userInfoRedisService.setVerifyCode(phone,code);
    }

    @Override
    public void userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) throws LogicException{
        //判断参数是否为空
        AssertUtil.hasLength(phone,"手机号码不能为空");
        AssertUtil.hasLength(nickname,"昵称不能为空");
        AssertUtil.hasLength(password,"密码能为空");
        AssertUtil.hasLength(rpassword,"确认密码不能为空");
        AssertUtil.hasLength(verifyCode,"验证码不能为空");
        //判断密码与确认密码是否一致
        AssertUtil.isEquals(password,rpassword,"两次输入密码不一致");
        //判断手机号码是否符合要求
        String regex = "^1[3|4|5|7|8][0-9]\\d{4,8}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phone);
        boolean isMatch = matcher.matches();
        if(!isMatch){
            throw new LogicException("手机号格式不正确");
        }
        //判断是否存在该手机号码
        if (checkPhone(phone)) {
            throw new LogicException("该手机号码已存在");
        }
        //判断手机号和验证码、时间是否符合要求
        String code = userInfoRedisService.getVerifyCode(phone);
        AssertUtil.hasLength(code,"验证码错误");
        AssertUtil.isEquals(code,verifyCode,"验证码错误或失效");
        //注册
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setPassword(password);
        userInfo.setPhone(phone);
        userInfo.setLevel(1);  //用户级别
        userInfo.setState(userInfo.STATE_NORMAL);
        userInfo.setHeadImgUrl("/images/default.png");
        userInfoMapper.insert(userInfo);
    }

    @Override
    public String userLogin(String phone, String password) throws LogicException{
        //先查询账号密码是否存在
        UserInfo userInfo = userInfoMapper.selectByPhoneAndPassword(phone,password);
        if(userInfo == null){
            throw new LogicException("账号或密码错误");
        }
        if (LOGOFFSTATE==userInfo.getState()){
            throw new LogicException("该账户已注销");
        }
        //定一个值为UUID的token
        String token = UUID.randomUUID().toString().replaceAll("-","").substring(0,4);
        //缓存到redis中
        userInfoRedisService.setToken(token,userInfo);
        return token;
    }

    @Override
    public List<UserInfo> list() {
        return userInfoMapper.selectAll();
    }

    @Override
    public List<UserInfo> getIdol(Long[] longs) {
        return userInfoMapper.selectIdol(longs);
    }

    @Override
    public void updateUserInfo(UserInfo userInfo) {
        userInfoMapper.updateByPrimaryKey(userInfo);
    }

    @Override
    public void setNewPassword(UserInfo userInfo, String password,String rpassword, String verifyCode)  throws LogicException{
        if (!password.equals(rpassword)){
            throw new LogicException("两次密码输入不匹配,请重新输入");
        }
        String code = userInfoRedisService.getVerifyCode(userInfo.getPhone());
        if (!verifyCode.equals(code)){
            throw new LogicException("验证码不匹配,请重新输入");
        }
        userInfoMapper.updatePassword(userInfo.getPhone(),password);
    }

    @Override
    public boolean phoneVerify(String phone, String code) throws LogicException {
        String code1 = userInfoRedisService.getVerifyCode(phone);
        if (code1==null){
            throw new LogicException("账号对应手机不正确");
        }
        if (!code.equals(code1)){
            throw new LogicException("验证码错误,请核对后再输入");
        }
        return true;
    }

    @Override
    public boolean updatePhone(Long id, String phone, String code)throws LogicException {
        String code1 = userInfoRedisService.getVerifyCode(phone);
        if (code1==null){
            throw new LogicException("请点击发送验证码");
        }
        if (!code.equals(code1)){
            throw new LogicException("验证码错误,请核对后再输入");
        }
        //查询更改的手机号是否已被注册
        int i = userInfoMapper.selectByPhone(phone);
        if (i>0){
            //该手机号已被注册
            throw  new LogicException("该手机已被注册,请更换手机号码");
        }
        userInfoMapper.updatePhoneById(id,phone);
        return true;
    }

    @Override
    public void logoff(UserInfo userInfo, String token) {
        //伪删除,将state改成-1
        userInfoMapper.updateState(userInfo);
        //清除redis中的userInfo
        userInfoRedisService.deleteUserInfo(token);
    }
}
